package com.asset.dispoal.file.appoint.service.command;

import com.alibaba.excel.EasyExcel;
import com.asset.dispoal.business.appoint.service.command.InsertAppointCommand;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.commom.menus.AgreementCaseSateMenu;
import com.asset.dispoal.file.appoint.dto.AppointImportRequest;
import com.asset.dispoal.file.evidenceRecognition.domain.dto.IdCard;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FileAppointImportCommand implements BaseCommand<AppointImportRequest, Result> {

    @Autowired
    InsertAppointCommand insertAppointCommand;

    @Autowired
    BsCaseMapper caseMapper;


    @SneakyThrows
    @Override
    public Result execute(AppointImportRequest request) {
        List<IdCard> idCardList = EasyExcel.read(request.getFile().getInputStream()).head(IdCard.class).sheet().doReadSync();
        if (CollectionUtil.isEmpty(idCardList)) {
            return Result.faild("模板不存在身份证号");
        }
        Set<String> idCardSet = idCardList.stream().map(IdCard::getIdCard).collect(Collectors.toSet());
        AgreementCaseSateMenu state;
        if ("1".equals(request.getType())) {
            state = AgreementCaseSateMenu.WAIT_DELIVERY;
        } else if ("2".equals(request.getType())) {
            state = AgreementCaseSateMenu.WITHDRAWAL;
        } else {
            state = AgreementCaseSateMenu.FLAW;
        }
        request.setCaseIdList(caseMapper.queryCaseIdByIdCardSetAndState(idCardSet, state.getLabel(), request.getAssetInstBatchId()));
        if (CollectionUtil.isNotEmpty(request.getCaseIdList())) {
            return insertAppointCommand.execute(request);
        }
        return Result.faild("没找到对应派出得数据");
    }
}
